from django.shortcuts import render, redirect, HttpResponse
from administrative.models import Company, User, Topicsattachments
from infrastructure_process.models import *
from django.views import View
import json, uuid, datetime, os, xlrd
from logistics.MessagePushOperationRecords import RecordAndPush
from announcements import public_file
from administrative.public_file import ParseWord, PDFConverter


class InfrastructureRenovationListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'infrastructure_process/InfrastructureRenovationList.html', {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        objs = user.infrastructuremaintenance_set.all().order_by('-create_time')
        data_list = [{'id': obj.id, 'reason': obj.reason, 'project_name': obj.project_name, 'cost_estimating': obj.cost_estimating, 'emergency': "是" if obj.emergency == '1' else '否',
                      'status': obj.get_state_str(), 'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='InfrastructureRenovationDraft.html?id={obj.id}'>编辑</a> | <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == 'draft'
                      else f"<a href='InfrastructureRenovationDetail.html?id={obj.id}'>查看</a> | <a href='InfrastructureRenovationDetail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state not in ['draft', 'stop']
                      else f"<a href='InfrastructureRenovationDetail.html?id={obj.id}'>查看</a> |  <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == "stop" else f"<a href='InfrastructureRenovationDetail.html?id={obj.id}'>查看</a>",
                      'state': obj.get_state_str(), "title": obj.reason} for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class InfrastructureRenovationIndexView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'infrastructure_process/InfrastructureRenovationIndex.html',
                      {'realname': real_name, 'position': position, 'department': department, "uuid": uuid.uuid4(), "my_obj": request.user, "apply_time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M")})

    def post(self, request):
        flow_id = request.POST.get('id', None)
        fj_number = request.POST.get("fj_number", "")
        reason = request.POST.get("reason", "")
        emergency = request.POST.get("emergency", "")
        note = request.POST.get("note", "")
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "科研经费")
        except:
            pass

        if flow_id:
            obj = InfrastructureMaintenance.objects.get(id=int(flow_id))
            obj.reason = reason
            obj.emergency = emergency
            obj.note = note
            obj.save()
            obj.current_audit_users.clear()
            obj.infrastructuremaintenancerecord_set.filter(state='unaudit').delete()
            message_str = "修改成功"
        else:
            obj = InfrastructureMaintenance.objects.create(apply_user=request.user, company=request.user.company, mobile=request.user.mobile, fj_number=fj_number, reason=reason, emergency=emergency, note=note)
            message_str = "创建成功"

        one_step = Company.objects.get(id=28).head_people
        InfrastructureMaintenanceRecord.objects.create(node='one', audit_note='', audit_people=one_step, parent_id=obj)
        obj.state = 'one'
        obj.current_audit_users.add(one_step)

        two_setp = request.user.company.head_people
        InfrastructureMaintenanceRecord.objects.create(node='two', audit_note='', audit_people=two_setp, parent_id=obj)

        three_setp = request.user.company.leaders_id
        InfrastructureMaintenanceRecord.objects.create(node='three', audit_note='', audit_people=three_setp, parent_id=obj)

        four_setp = Company.objects.get(id=28).leaders_id
        InfrastructureMaintenanceRecord.objects.create(node='four', audit_note='', audit_people=four_setp, parent_id=obj)
        obj.save()
        returnDict = {'status': 'success', 'message': message_str, 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class InfrastructureRenovationDraftView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        obj = InfrastructureMaintenance.objects.get(id=flow_id)

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, "file_list": file_list}
        return render(request, 'infrastructure_process/InfrastructureRenovationDraft.html', context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        fj_number = request.POST.get("fj_number", "")
        reason = request.POST.get("reason", "")
        emergency = request.POST.get("emergency", "")
        note = request.POST.get("note", "")
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "科研经费")
        except:
            pass

        if flow_id:
            obj = InfrastructureMaintenance.objects.get(id=int(flow_id))
            obj.reason = reason
            obj.emergency = emergency
            obj.note = note
            obj.save()
        else:
            obj = InfrastructureMaintenance.objects.create(apply_user=request.user, company=request.user.company, mobile=request.user.mobile, fj_number=fj_number, reason=reason, emergency=emergency, note=note)
        obj.state = 'draft'
        obj.save()
        returnDict = {'status': 'success', 'message': "", 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class InfrastructureRenovationDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = InfrastructureMaintenance.objects.get(id=flow_id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.infrastructuremaintenancerecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append(
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.infrastructuremaintenancerecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                     'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                     'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true' if (obj.state == 'refuse' and obj.apply_user == request.user) or revise else 'false', 'flow_dict': flow_dict, "revise": revise,
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four'] and request.user == obj.apply_user else 'false',
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'infrastructure_process/InfrastructureRenovationDetail.html', context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "基建维修改造")
        except:
            pass
        obj = InfrastructureMaintenance.objects.get(id=int(flow_id))

        if not obj.infrastructuremaintenancerecord_set.filter(node=obj.state, state='unaudit', audit_people=request.user).count():
            returnData = {'code': 400, 'message': '该流程已审核，请勿重复点击！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.infrastructuremaintenancerecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                project_name = request.POST.get("project_name", '')
                cost_estimating = request.POST.get("cost_estimating", '')
                completion_time = request.POST.get("completion_time", '')
                budget_details = request.POST.get("budget_details", '')
                obj.project_name = project_name
                obj.cost_estimating = cost_estimating
                obj.completion_time = completion_time
                obj.budget_details = budget_details
                obj.save()
                next_audit_record = obj.infrastructuremaintenancerecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)

                file_lenth = request.POST.get('file_lenth', '')
                fj_number = request.POST.get('fj_number', '')
                for i in range(int(file_lenth)):
                    files = request.FILES.get(f'file{i}')
                    file_obj = Topicsattachments.objects.create(
                        topics_number=fj_number, file_size=public_file.StrOfSize(files.size), file_path=files, uploader=request.user.username,
                        uploader_user=request.user, file_type=1, is_deleted=False, source='JJWXGZ'
                    )
                    sys_path = os.getcwd()
                    file_name = files.name
                    file_obj.file_name = file_name
                    file_obj.save()

                    word_path = sys_path + '/media/' + str(file_obj.file_path)
                    old_word_path = word_path
                    temp_name = os.path.splitext(file_name)[0]
                    new_word_path = old_word_path.replace(os.path.splitext(file_obj.file_path.name.split("/")[-1])[0], temp_name)
                    os.rename(old_word_path, new_word_path)
                    word_path = new_word_path

                    file_path = file_obj.file_path.name.replace(
                        os.path.splitext(file_obj.file_path.name.split("/")[-1])[0], temp_name)

                    pdf_path = word_path
                    if word_path.split('.')[-1] in ['docx', 'doc', 'DOC', 'DOCX']:
                        pdf_path = ParseWord().word2pdf(word_path)
                    elif word_path.split(".")[-1] in ['ppt', 'pptx']:
                        pdf_path = ParseWord().ppt2pdf(word_path)
                    elif word_path.split(".")[-1] in ['xls', 'xlsx', 'XLS', 'XLSX']:
                        b = xlrd.open_workbook(word_path)
                        sheetnum = len(b.sheets())
                        pdfConverter = PDFConverter(word_path, sheetnum, os.path.splitext(file_name)[0])
                        pdf_path = pdfConverter.run_conver()
                    else:
                        pdf_path = '/media/' + str(file_path)
                    pdf_list = []
                    if type(pdf_path) is list:
                        for i in range(len(pdf_path)):
                            if i == 0:
                                file_obj.pdf_path = pdf_path[i].replace(os.getcwd(), '')
                                tic_id = file_obj.id
                                file_obj.save()
                            else:
                                all_file = Topicsattachments.objects.create(topics_number=fj_number, file_path=files, file_size=public_file.StrOfSize(files.size), uploader=request.user.username,
                                    file_type=1, pdf_path=pdf_path[i].replace(os.getcwd(), ''), file_name=os.path.split(pdf_path[i])[1], source="JJWXGZ", uploader_user=request.user.username
                                )
                                tic_id = all_file.id
                            one_dict = {"id": tic_id, 'pdf_path': pdf_path[i].replace(os.getcwd(), '')}
                            pdf_list.append(one_dict)
                    else:
                        fileName = pdf_path.split("/")[-1].split(".")[0]
                        pdf_path = pdf_path.replace(fileName, files.name.split(".")[0]).replace(os.getcwd(), "")
                        pdf_path = pdf_path.replace(os.path.splitext(os.path.split(pdf_path)[1])[0], os.path.splitext(file_name)[0])
                        file_obj.pdf_path = pdf_path
                        file_obj.save()
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.infrastructuremaintenancerecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.infrastructuremaintenancerecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.infrastructuremaintenancerecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.infrastructuremaintenancerecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.infrastructuremaintenancerecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                obj_state = 'end'
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "基建维修改造"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.reason[:15] + "……" if len(obj.reason) > 15 else obj.reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class InfrastructureRenovationStopView(View):
    def post(self, request):
        flow_id = request.POST.get('id', '')
        types = request.POST.get('types', '')
        obj = InfrastructureMaintenance.objects.get(id=int(flow_id))
        if obj.state == 'end':
            returnData = {'code': 500, 'message': '操作失败，已完结流程无法操作！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        obj.current_audit_users.clear()
        if types == 'stop':
            obj.state = 'stop'
            obj.save()
            returnData = {'code': 200, 'message': '终止成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            obj.infrastructuremaintenancerecord_set.all().delete()
            obj.audit_users_already.clear()
            obj.delete()
            returnData = {'code': 200, 'message': '删除成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")


class ProfessionalServicesListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'infrastructure_process/ProfessionalServicesList.html', {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        objs = user.professionalservices_set.all().order_by('-create_time')
        data_list = [{'id': obj.id, 'reason': obj.reason, 'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"), 'service_content': obj.service_content, 'budget_amount': obj.budget_amount,
                      'status': obj.get_state_str(), 'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='ProfessionalServicesDraft.html?id={obj.id}'>编辑</a> | <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == 'draft'
                      else f"<a href='ProfessionalServicesDetail.html?id={obj.id}'>查看</a> | <a href='ProfessionalServicesDetail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state not in ['draft', 'stop']
                      else f"<a href='ProfessionalServicesDetail.html?id={obj.id}'>查看</a> |  <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == "stop" else f"<a href='ProfessionalServicesDetail.html?id={obj.id}'>查看</a>",
                      } for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ProfessionalServicesIndexView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'infrastructure_process/ProfessionalServicesIndex.html', {'realname': real_name, 'position': position, 'department': department, "uuid": uuid.uuid4(), "my_obj": request.user, "apply_time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M")})

    def post(self, request):
        flow_id = request.POST.get('id', None)
        fj_number = request.POST.get("fj_number", "")
        reason = request.POST.get("reason", "")
        service_content = request.POST.get("service_content", "")
        budget_amount = request.POST.get("budget_amount", "")
        amount_words = request.POST.get("amount_words", "")
        note = request.POST.get("note", "")
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "基建项目专业服务")
        except:
            pass

        if flow_id:
            obj = ProfessionalServices.objects.get(id=int(flow_id))
            obj.reason = reason
            obj.service_content = service_content
            obj.budget_amount = budget_amount
            obj.amount_words = amount_words
            obj.note = note
            obj.save()
            obj.current_audit_users.clear()
            obj.professionalservicesrecord_set.filter(state='unaudit').delete()
            message_str = "修改成功"
        else:
            obj = ProfessionalServices.objects.create(apply_user=request.user, company=request.user.company, mobile=request.user.mobile, fj_number=fj_number, reason=reason,
                                                      service_content=service_content, budget_amount=budget_amount, amount_words=amount_words, note=note)
            message_str = "创建成功"

        flag = True
        one_step = request.user.company.head_people
        if request.user != one_step:
            ProfessionalServicesRecord.objects.create(node='one', audit_note='', audit_people=one_step, parent_id=obj)
            obj.state = 'one'
            obj.current_audit_users.add(one_step)
            flag = False

        two_flag = True
        two_setp = Company.objects.get(id=28).head_people
        if request.user != two_setp:
            ProfessionalServicesRecord.objects.create(node='two', audit_note='', audit_people=two_setp, parent_id=obj)
            if flag:
                obj.state = 'two'
                obj.current_audit_users.add(two_setp)
                two_flag = False

        three_setp = Company.objects.get(id=28).leaders_id
        ProfessionalServicesRecord.objects.create(node='three', audit_note='', audit_people=three_setp, parent_id=obj)
        if flag and two_flag:
            obj.state = 'three'
            obj.current_audit_users.add(three_setp)

        obj.save()
        returnDict = {'status': 'success', 'message': message_str, 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ProfessionalServicesDraftView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        obj = ProfessionalServices.objects.get(id=flow_id)

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, "file_list": file_list}
        return render(request, 'infrastructure_process/ProfessionalServicesDraft.html', context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        fj_number = request.POST.get("fj_number", "")
        reason = request.POST.get("reason", "")
        service_content = request.POST.get("service_content", "")
        budget_amount = request.POST.get("budget_amount", "")
        amount_words = request.POST.get("amount_words", "")
        note = request.POST.get("note", "")
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "基建项目专业服务")
        except:
            pass

        if flow_id:
            obj = ProfessionalServices.objects.get(id=int(flow_id))
            obj.reason = reason
            obj.service_content = service_content
            obj.budget_amount = budget_amount
            obj.amount_words = amount_words
            obj.note = note
            obj.save()
            message_str = "修改成功"
        else:
            obj = ProfessionalServices.objects.create(apply_user=request.user, company=request.user.company, mobile=request.user.mobile, fj_number=fj_number, reason=reason,
                                                      service_content=service_content, budget_amount=budget_amount, amount_words=amount_words, note=note)
            message_str = "创建成功"
        obj.state = 'draft'
        obj.save()
        returnDict = {'status': 'success', 'message': message_str, 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ProfessionalServicesDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = ProfessionalServices.objects.get(id=flow_id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.professionalservicesrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append(
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.professionalservicesrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                     'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                     'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true' if (obj.state == 'refuse' and obj.apply_user == request.user) or revise else 'false',
                   'flow_dict': flow_dict, "revise": revise,
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three'] and request.user == obj.apply_user else 'false',
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'infrastructure_process/ProfessionalServicesDetail.html', context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "基建维修改造")
        except:
            pass
        obj = ProfessionalServices.objects.get(id=int(flow_id))

        if not obj.professionalservicesrecord_set.filter(node=obj.state, state='unaudit', audit_people=request.user).count():
            returnData = {'code': 400, 'message': '该流程已审核，请勿重复点击！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.professionalservicesrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                if obj.professionalservicesrecord_set.filter(node='two', state='unaudit').count():
                    next_audit_record = obj.professionalservicesrecord_set.filter(node='two', state='unaudit').first()
                    obj_state = 'two'
                else:
                    next_audit_record = obj.professionalservicesrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.professionalservicesrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.professionalservicesrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.professionalservicesrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                obj_state = 'end'
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "基建项目专业服务"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.reason[:15] + "……" if len(obj.reason) > 15 else obj.reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class ProfessionalServicesStopView(View):
    def post(self, request):
        flow_id = request.POST.get('id', '')
        types = request.POST.get('types', '')
        obj = ProfessionalServices.objects.get(id=int(flow_id))
        if obj.state == 'end':
            returnData = {'code': 500, 'message': '操作失败，已完结流程无法操作！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        obj.current_audit_users.clear()
        if types == 'stop':
            obj.state = 'stop'
            obj.save()
            returnData = {'code': 200, 'message': '终止成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            obj.professionalservicesrecord_set.all().delete()
            obj.audit_users_already.clear()
            obj.delete()
            returnData = {'code': 200, 'message': '删除成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")



